local skynet = require "skynet"
local filelog = require "filelog"
local configdao = require "configdao"
local msgproxy = require "msgproxy"
local timetool = require "timetool"
local helperbase = require "helperbase"
local playerdatadao = require "playerdatadao"
local base = require "base"
local gamelog = require "gamelog"
local json = require "cjson"
local marquee = require "marquee"
local md5 = require "md5" 
require "enum"

json.encode_sparse_array(true,1,1)
local trace_rids = nil
local selfbuildtablecfg = nil
local AgentHelper = helperbase:new({}) 

--用于输出指定rid玩家的信息，方便定位问题
function AgentHelper:write_agentinfo_log(...)
	if trace_rids == nil then
		trace_rids = configdao.get_common_conf("rids")
	end

	if trace_rids == nil then
		return
	end

	local rid = self.server.rid
	if (trace_rids.isall ~= nil and trace_rids.isall) or trace_rids[rid] ~= nil then
		filelog.sys_obj("agent", rid, ...)	
	end	
end

--用于copy玩家的基本信息
function AgentHelper:copy_base_info(baseinfo, info, playgame, money)
	baseinfo.rid = info.rid
	-- if info.rolename == "_guest" then
	-- 	info.rolename = "游客"..tostring(info.rid%10000)
	-- end
	baseinfo.rolename = info.rolename
    baseinfo.logo = info.logo
    baseinfo.phone = info.phone
    baseinfo.sex = info.sex
    baseinfo.invitecode = info.invitecode
    baseinfo.agentlevel = info.agentlevel
    baseinfo.gemstone = money.gemstone 
    baseinfo.coin = money.coin
    baseinfo.roomcard = money.roomcard
    baseinfo.lottery = money.lottery
    baseinfo.maxgemstone = money.maxgemstone
    baseinfo.maxcoinnum = money.maxcoinnum
    baseinfo.maxroomcard = money.maxroomcard
    baseinfo.maxlottery = money.maxlottery
    baseinfo.gameid = self.server.gameid
    baseinfo.ip = self.server.ip
    if playgame ~= nil then
    	baseinfo.playgame = json.encode(playgame.playgame)
    end
end

--判断玩家是否登陆成功
function AgentHelper:is_login_success()
	return  (self.server.state == EGateAgentState.GATE_AGENTSTATE_LOGINED) 
end

--判断玩家是否退出成功
function AgentHelper:is_logout_success()
	return  (self.server.state == EGateAgentState.GATE_AGENTSTATE_LOGOUTED) 
end

function AgentHelper:save_player_gameInfo(rid,key_value_table,reason)
	local playgame = self.server.playgame
	playerdatadao.save_player_playgame("update",rid,self.server.playgame)
end

function AgentHelper:save_player_coin(rid, number, reason, key)
	local money = self.server.money
	local beforetotal = money.coin
	local aftertotal = 0
	if money.coin + number >= 0 then
		money.coin = money.coin + number
		if money.coin > money.maxcoinnum then money.maxcoinnum = money.coin end
	else
		money.coin = 0
	end
	aftertotal = money.coin
	playerdatadao.save_player_money("update", rid, self.server.money)
	gamelog.write_player_coinlog(rid, reason, key, number, beforetotal, aftertotal)

	self:update_rank_list(ERankListType.ERANKLISTTYPE_COIN, money.coin, 1, 0, 0)
end

function AgentHelper:save_player_gemstone(rid, number, reason, key, money)
	money = money or self.server.money
	local beforetotal = 0
	local aftertotal = 0
	if money.gemstone + number >= 0 then
		money.gemstone = money.gemstone + number
		if money.gemstone > money.maxgemstone then money.maxgemstone = money.gemstone end
	else
		money.gemstone = 0
	end
	aftertotal = money.gemstone
	playerdatadao.save_player_money("update", rid, money)
	gamelog.write_player_gemstonelog(rid, reason, key, number, beforetotal, aftertotal)
end

function AgentHelper:save_player_roomcard(rid, number, reason, key, money)
	money = money or self.server.money
	local beforetotal = 0
	local aftertotal = 0
	if money.roomcard + number >= 0 then
		money.roomcard = money.roomcard + number
		if money.roomcard > money.maxroomcard then money.maxroomcard = money.roomcard end
	else
		money.roomcard = 0
	end
	aftertotal = money.roomcard
	playerdatadao.save_player_money("update", rid, money)
	gamelog.write_player_roomcardlog(rid, reason, key, number, beforetotal, aftertotal)
end

function AgentHelper:save_player_lottery(rid, number, reason, key, money)
	money = money or self.server.money
	local beforetotal = 0
	local aftertotal = 0
	if money.lottery + number >= 0 then
		money.lottery = money.lottery + number
		if money.lottery > money.maxlottery then money.maxlottery = money.lottery end
	else
		money.lottery = 0
	end
	aftertotal = money.lottery
	playerdatadao.save_player_money("update", rid, money)
	gamelog.write_player_lotterylog(rid, reason, key, number, beforetotal, aftertotal)

	self:update_rank_list(ERankListType.ERANKLISTTYPE_LOTTERY, money.lottery, 1, 0, 0)
end

function AgentHelper:save_player_awards(rid, awards, reason, key)
	if awards == nil then
		return
	end

	local is_coinchange = false
	local is_roomcardchange = false
	local is_gemstonechange = false
	local is_lotterychange = false
	for _, award in ipairs(awards) do
		if award.id == ECurrencyType.CURRENCY_TYPE_COIN then
			self:save_player_coin(rid, award.num, reason, key)
			is_coinchange = true
		elseif award.id == ECurrencyType.CURRENCY_TYPE_GEMSTONE then
			self:save_player_gemstone(rid, award.num, reason, key)
			is_gemstonechange = true
		elseif award.id == ECurrencyType.CURRENCY_TYPE_ROOMCARD then
			self:save_player_roomcard(rid, award.num, reason, key)
			is_roomcardchange = true			
		elseif award.id == ECurrencyType.CURRENCY_TYPE_LOTTERY then
			self:save_player_lottery(rid, award.num, reason, key)
			is_lotterychange = true			
		else
			--TO ADD 操作道具
		end
	end

	if is_coinchange then
		self:send_coinchange_notice()
	end

	if is_gemstonechange then
		self:send_gemstonechange_notice()
	end

	if is_roomcardchange then
		self:send_roomcardchange_notice()
	end

	if is_lotterychange then
		self:send_lotterychange_notice()
	end
end

--- 生成邮件接口
-- @param rid
-- @param mailtable 邮件结构
-- @param reason
--
function AgentHelper:generate_mail(rid,mailtable,reason)
	if not rid or rid <= 0 or type(mailtable) ~= "table" then return end
	mailtable.mail_key = base.generate_uuid()
	mailtable.rid = rid
	mailtable.create_time = timetool.get_time()
	mailtable.reason = reason or ESendMailReasonType.COMMON_TYPE_TESTING
	playerdatadao.save_player_mail("insert",rid,mailtable,nil)
end

function AgentHelper:get_selfbuildtablecfgitem(gameid)
	if selfbuildtablecfg == nil then
		selfbuildtablecfg = configdao.get_business_conf(100, 1000, "selfbuildtablecfg")
	end
	if selfbuildtablecfg == nil then
		return nil
	end

	for _, selfbuildtablecfgitem in pairs(selfbuildtablecfg) do
		if gameid == selfbuildtablecfgitem.gameid then
			return selfbuildtablecfgitem
		end
	end
	return nil
end

function AgentHelper:send_gemstonechange_notice()
	local money = self.server.money
	local noticemsg = {
		gemstone = money.gemstone,
	}
	self:send_noticemsgto_client(nil, "PlayerGemstoneNtc", noticemsg)
end

function AgentHelper:send_coinchange_notice()
	local money = self.server.money
	local noticemsg = {
		coin = money.coin,
	}
	self:send_noticemsgto_client(nil, "PlayerCoinNtc", noticemsg)	
end

function AgentHelper:send_roomcardchange_notice()
	local money = self.server.money
	local noticemsg = {
		roomcard = money.roomcard,
	}
	self:send_noticemsgto_client(nil, "PlayerRoomcardNtc", noticemsg)	
end

function AgentHelper:send_lotterychange_notice()
	local money = self.server.money
	local noticemsg = {
		lottery = money.lottery,
	}
	self:send_noticemsgto_client(nil, "PlayerLotteryNtc", noticemsg)	
end

function AgentHelper:triggermarquee(config_id, match_name, match_start_countdown, trigger_region_value, option_data, conditions)
    local eventmsg = {
		config_id = config_id,
		match_name=match_name,
		match_start_countdown=match_start_countdown,        --比赛开始倒计时,时间差单位s
		rolename=self.server.info.rolename,   --玩家角色名
		trigger_region_value=trigger_region_value, --触发区域
		option_data=option_data,
		conditions = conditions,
		id = marquee.generate_id(),
    }
    marquee.triggermarquee(eventmsg)

    local svrs = configdao.get_svrs("gatesvrs")
    for svr_id, _ in pairs(svrs) do
    	if svr_id ~= skynet.getenv("svr_id") then
    		msgproxy.sendrpc_noticemsgto_gatesvrd(svr_id, svr_id, "triggermarquee", eventmsg)
    	end
    end
end

--上报排行榜
function AgentHelper:update_rank_list(rank_key, rankval, addtype, addgamenumber, addmttnumber)
	local server = self.server
	local updaterankinfo ={
		rank_key = 0,
		rid   = 0,
		rankval_addtype = 1,--1更新 2直接覆盖数据
		rankval = 0,
		rolename = "",
		logo = "",
		sex  = 0,
		addgamenumber = 0,
		addmttnumber  = 0,
	}

	updaterankinfo.rank_key 		= rank_key  --游戏场-参赛总场次
	updaterankinfo.rid      		= rid
	updaterankinfo.rankval_addtype  = addtype or 1
	updaterankinfo.rankval      	= rank_key
	updaterankinfo.rolename     	= self.server.info.rolename
	updaterankinfo.logo     		= self.server.info.logo
	updaterankinfo.sex     			= self.server.info.sex
	updaterankinfo.addgamenumber 	= addgamenumber or 0
	updaterankinfo.addmttnumber     = addmttnumber or 0

	msgproxy.sendrpc_noticemsgto_ranklistsvrd("update",updaterankinfo)
end  

function AgentHelper:generate_zhuanzhang_password(cpass)
	local slatstr = cpass
	slatstr = slatstr.."&"..tostring(self.server.rid).."&2016"
	return md5.sumhexa(slatstr) 
end

return AgentHelper